package com.example.common.xss;


import com.example.common.exception.BusinessException;
import com.example.common.response.ComResponseEnum;
import org.apache.commons.text.StringEscapeUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 用于普通多参数的HttpServletRequest
 *
 * @author wangxiaoyun
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private SensitiveWord sensitiveword;

    public XssHttpServletRequestWrapper(HttpServletRequest request, SensitiveWord sf) {
        super(request);
        sensitiveword = sf;
    }

    @Override
    public String getHeader(String name) {
        return StringEscapeUtils.escapeHtml4(super.getHeader(name));
    }

    @Override
    public String getQueryString() {
        return super.getQueryString() == null ? "" : SequenceTool.xssEncode(super.getQueryString()).toString();
    }

    @Override
    public String getParameter(String name) {
        return StringEscapeUtils.escapeHtml4(super.getParameter(name));
    }

    @Override
    public String[] getParameterValues(String name) {

        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++) {
                //判断是否包含敏感字符
                if (sensitiveword.getSensitiveWord(values[i], 1).size() > 0) {
                    throw new BusinessException(ComResponseEnum.SENSITIVE);
                }
                escapseValues[i] = SequenceTool.xssEncode(values[i]).toString();
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }
}
